package jetbrains.buildServer.cuta.logic.operators;

import jetbrains.buildServer.cuta.logic.ColumnDef;
import jetbrains.buildServer.cuta.logic.sheet.Cell;
import jetbrains.buildServer.serverSide.SBuildAgent;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;

import java.util.Map;

import static jetbrains.buildServer.cuta.utils.DomUtil.getAttrString;



/**
 * @author Leonid Bushuev from JetBrains
 */
abstract class GetAgentVarOperator extends AbstractOperator
{
    private String myVarName = "";
    private String myDefaultValue = null;


    @Override
    public void init(Element element, ColumnDef column, ExternalContext extContext)
    {
        myVarName = getAttrString(element, "name", "");
        myDefaultValue = getAttrString(element, "default", null);
    }


    @Override
    public void run(Object object, Cell cell)
    {
        String value;
        if (object instanceof SBuildAgent)
        {
            SBuildAgent agent = (SBuildAgent) object;
            String confParamName = getNamePrefix() + myVarName;
            value = getVars(agent).get(confParamName);
            if (value == null)
                value = myDefaultValue;
        }
        else
        {
            value = name() + " is not applicable to " + object.getClass().getSimpleName();
        }

        cell.addText(value);
    }


    @NotNull
    protected abstract Map<String,String> getVars(SBuildAgent agent);

    @NotNull
    protected abstract String getNamePrefix();



    @Override
    public String toString()
    {
        return name() + " " + myVarName;
    }
}
